﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Model;
using Model.Models;
using Persistence;
namespace Services
{
    /// <summary>
    /// Gerencia todas as regras de negócio da entidade Status
    /// </summary>
    public class GerenciadorStatus
    {
        private IUnitOfWork unitOfWork;
        private bool shared;

        public GerenciadorStatus()
        {
            this.unitOfWork = new UnitOfWork();
            shared = false;
        }

        internal GerenciadorStatus(IUnitOfWork unitOfword)
        {
            this.unitOfWork = unitOfword;
            shared = true;
        }

        public int Inserir(Status statusModel)
        {
            TB_STATUS statusE = new TB_STATUS();
            Atribuir(statusModel, statusE);
            unitOfWork.RepositorioStatus.Inserir(statusE);
            unitOfWork.Commit(shared);
            return statusE.id_Status;

        }


        public void Editar(Status statusModel)
        {
            TB_STATUS statusE = new TB_STATUS();
            Atribuir(statusModel, statusE);
            unitOfWork.RepositorioStatus.Editar(statusE);
            unitOfWork.Commit(shared);
        }

        public void Remover(int idStatus)
        {
            unitOfWork.RepositorioStatus.Remover(status => status.id_Status.Equals(idStatus));
            unitOfWork.Commit(shared);

        }

        private IQueryable<Status> GetQuery()
        {
            IQueryable<TB_STATUS> tb_status = unitOfWork.RepositorioStatus.GetQueryable();
            var query = from status in tb_status
                        select new Status
                        {
                            Id_Status = status.id_Status,
                            Id_Empresa = status.id_Empresa,
                            Descricao = status.descricao,
                            NomeEmpresa = status.TB_EMPRESA.nome
                        };
            return query;
        }

        public IEnumerable<Status> ObterTodos()
        {
            return GetQuery();
        }

        public Status Obter(int idStatus)
        {
            IEnumerable<Status> statusEs = GetQuery().Where(statusModel => statusModel.Id_Status.Equals(idStatus));
            return statusEs.ElementAtOrDefault(0);
        }


        private void Atribuir(Status statusModel, TB_STATUS statusE)
        {
            statusE.id_Status = statusModel.Id_Status;
            statusE.id_Empresa = statusModel.Id_Empresa;
            statusE.descricao = statusModel.Descricao;
        }
    }
}